from datetime import datetime

import snowflake.client
from flask import render_template, flash, request, redirect, url_for, abort
from flask_login import login_required, current_user

from ..modle import TPassage, TPassageSource
from .forms import postForm
from .. import db

from . import passageprint as passagesview


@passagesview.route('/search_passage', methods=['GET', 'POST'])
def search_passage():
    passage_name = request.args.get('passage_name', '', type=str)
    page = request.args.get('page', 1, type=int)
    passage = db.session.query(TPassage).filter(TPassage.passage_name.like('%' + passage_name + '%')) \
        .paginate(page, per_page=10, error_out=False)
    passage_info = passage.items
    return render_template('searchlist.html', passage_info=passage_info,
                           pagination=passage, endpoint='passagesview.search_passage',
                           keyword=passage_name)


@passagesview.route('/MyPost', methods=['GET', 'POST'])
@login_required
def my_post():
    user_id = request.args.get('username', current_user.user_id, type=str)
    if user_id is None or user_id != current_user.user_id:
        return abort(404)
    page = request.args.get('page', 1, type=int)
    passage = TPassage.query.filter_by(passage_publicer=user_id).paginate(page, per_page=5, error_out=False)
    passage_info = passage.items
    return render_template("my_post.html", passage_info=passage_info,
                           pagination=passage, endpoint='passagesview.my_post')


@passagesview.route('/view/passage/<passage_name>')
def view_the_passage(passage_name):
    passage_info = TPassage.query.filter_by(passage_name=passage_name).first()
    passage_body = TPassageSource.query.filter_by(passage_id=passage_info.passage_id).first()
    return render_template('view_the_passage.html', passage=[passage_info, passage_body])


@passagesview.route('/edict/passage/', methods=['GET', 'POST'])
@login_required
def change_passage():
    user_id = request.args.get('userid', '', type=str)
    passage_id = request.args.get('passageid', '', type=str)
    if len(passage_id) == 0 or user_id != current_user.user_id:
        abort(404)
    passage = TPassage.query.filter_by(passage_id=passage_id).first()
    if user_id != passage.passage_publicer:
        abort(404)
    passage_source = TPassageSource.query.filter_by(passage_id=passage.passage_id).first()
    passageform = postForm()
    if passageform.validate_on_submit():
        # 检验文章合法性
        if len(passageform.passage_body.data) <= 20:
            flash('文章内容过少')
        passage.passage_name = passageform.passage_title.data
        passage.passage_somesource = passageform.passage_body.data[0:50]
        passage_source.passage_source_md = passageform.passage_body.data
        db.session.add(passage)
        db.session.commit()
        db.session.add(passage_source)
        db.session.commit()
        flash('成功修改！')
        return render_template('edict_passage.html', form=passageform, current_time=datetime.now())
    passageform.passage_title.data = passage.passage_name
    passageform.passage_body.data = passage_source.passage_source_md
    return render_template('edict_passage.html', form=passageform, current_time=datetime.now())


def is_owner(user_id, passage_id):
    passage = TPassage.query.filter_by(passage_id=passage_id).first()
    if passage.passage_publicer != user_id:
        return False
    return True


@passagesview.route('/delect_passage', methods=['GET', 'POST'])
@login_required
def delect_passage():
    user_id = request.args.get('userid', '', type=str)
    passage_id = request.args.get('passageid', '', type=str)
    if len(passage_id) == 0 or user_id != current_user.user_id:
        abort(404)
    if not is_owner(user_id, passage_id):
        abort(404)
    passage_source = TPassageSource.query.filter_by(passage_id=passage_id).first()
    passage = TPassage.query.filter_by(passage_id=passage_id).first()
    temp_passage_name = passage.passage_name
    db.session.delete(passage_source)
    db.session.commit()
    db.session.delete(passage)
    db.session.commit()
    flash('成功删除文章' + temp_passage_name)
    return redirect(url_for('passagesview.my_post', userid=current_user.user_id))


@passagesview.route('/createpassage', methods=['GET', 'POST'])
@login_required
def create_passage():
    passageform = postForm()
    if passageform.validate_on_submit():
        # 检验文章合法性
        if len(passageform.passage_body.data) <= 20:
            flash('文章内容过少')
            return render_template('edict_passage.html', form=passageform, current_time=datetime.now())

        # 通过pysnowflake服务获取雪花数
        passage_id = snowflake.client.get_guid()
        passage_publicer = current_user.user_id
        passage_name = passageform.passage_title.data
        passage_publictime = datetime.utcnow()
        passage_somesource = passageform.passage_body.data[0:50]
        passage_source_md = passageform.passage_body.data

        # 创建文章信息和文章体，并进行提交
        passage = TPassage(passage_id=passage_id, passage_publicer=passage_publicer,
                           passage_name=passage_name, passage_publictime=passage_publictime,
                           passage_somesource=passage_somesource)
        passage_source = TPassageSource(passage_id=passage_id, passage_source_md=passage_source_md)
        db.session.add(passage)
        db.session.commit()
        db.session.add(passage_source)
        db.session.commit()
        flash('成功添加文章')
        passageform.passage_title.data = ''
        passageform.passage_body.data = ''
        return render_template('edict_passage.html', form=passageform, current_time=datetime.now())
    return render_template('edict_passage.html', form=passageform, current_time=datetime.now())
